import {exec} from 'child_process';
import {logger} from "@/main/log.js";
import store, {store_field_lcu_certificate} from "@/main/store/store.js";


const windowsCommand = `"C:\\Windows\\System32\\wbem\\wmic" PROCESS WHERE "name=\'LeagueClientUx.exe\'" GET commandline`;

//获取英雄联盟客户端token
export function getLeagueClientCertificate() {
    return new Promise((resolve, reject) => {
            let token = null;
            let port = null;

            if (process.env.DEV_ENV === 'VIRTUAL') {
                logger.debug(`当前处于模拟环境`)
                resolve({
                    "token": 'mock token',
                    "port": 8888
                })
                return;
            }

            exec(
                windowsCommand,
                (err, stdout) => {
                    try {
                        if (stdout === undefined || stdout === "") {
                            throw new Error(`获取用户凭证失败,凭证为空,command:${windowsCommand}`)
                        }
                        token = stdout.match(/remoting-auth-token=(.*?)["'\s]/)[1];
                        port = stdout.match(/--app-port=(.*?)["'\s]/)[1];
                        logger.debug('get token',token,port, stdout)
                        resolve({
                            "token": token,
                            "port": port
                        })
                    } catch (err) {
                        logger.error(err);
                        reject(err);
                    }

                }
            );

        }
    )
}


export function getCredentials() {
    const token = store.get(`${store_field_lcu_certificate}.token`)
    const port = store.get(`${store_field_lcu_certificate}.port`)
    const auth = Buffer.from(`riot:${token}`).toString('base64');
    return {
        "port": port,
        "token": `Basic ${auth}`
    }
}

